package net

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"net"
)

func Ipv42Uint32(ipString string) uint32 {
	ip := net.ParseIP(ipString)
	if ip == nil {
		return 0
	}

	var ret uint32

	if err := binary.Read(bytes.NewBuffer(ip.To4()), binary.BigEndian, &ret); err != nil {
		return 0
	}

	return ret
}
func Uint322Ipv4(ipUint32 uint32) string {
	return fmt.Sprintf("%d.%d.%d.%d", byte(ipUint32>>24), byte(ipUint32>>16), byte(ipUint32>>8), byte(ipUint32))
}
func Ipv42Uint(ipString string) uint {
	return uint(Ipv42Uint32(ipString))
}
func Uint2Ipv4(ipUint uint) string {
	return Uint322Ipv4(uint32(ipUint))
}

func IsPrivateIP(ip net.IP) bool {
	if ip4 := ip.To4(); ip4 != nil {
		switch {
		case ip4[0] == 10:
			return true
		case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
			return true
		case ip4[0] == 192 && ip4[1] == 168:
			return true
		}
	}

	if ip6 := ip.To16(); ip6 != nil {
		if (ip6[0] & 0xfe) == 0xfc {
			return true
		}
	}

	return false
}

func testIp() {
	// ip := net.ParseIP("192.168.1.1")
	// ipRange := net.IPNet{
	// 	IP:   net.ParseIP("192.168.1.0"),
	// 	Mask: net.CIDRMask(24, 32),
	// }
	// if ipRange.Contains(ip) {
	// if ip2.Equal(ip) {
	// ip.String()
}

// [geoip2-golang](https://github.com/oschwald/geoip2-golang)
// [maxminddb-golang](https://github.com/oschwald/maxminddb-golang)
// [geolite2](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data)
// [GeoIP2](https://www.maxmind.com/en/solutions/ip-geolocation-databases-api-services)
